package cn.aylog.controller;

import cn.aylog.pojo.UploadFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

@RestController
@CrossOrigin
public class FileController {

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception{
        System.out.println(file.getOriginalFilename());
        Map<String, String[]> map = request.getParameterMap();
        UploadFile info = new UploadFile();
        info.setFile(file);
        Set<String> keySet = map.keySet();
        for(String prop : keySet) {
            Field field = info.getClass().getDeclaredField(prop);
            field.setAccessible(true);
            field.set(info, map.get(prop)[0]);
        }
        info.save();
        if(info.getCurrentSlice().equals(info.getTotalSlice())) {
            info.merge();
            return "merge complete";
        }
        return "SUCCESS";
    }

    @PostMapping("/upload2")
    public String upload2(@RequestParam MultipartFile file) {
        System.out.println(file.getOriginalFilename());
        return "SUCCESS";
    }

    @PostMapping("/upload3")
    public String upload3(@RequestParam("file") MultipartFile[] files) {
        for (int i=0; i<files.length; i++) {
            System.out.println(files[0].getOriginalFilename());
        }
        return "SUCCESS";
    }

    @RequestMapping("/test")
    public String test() {
        return "TEST";
    }



}
